<template>
  <div class="login-container">
    <div class="login-box">
      <!-- Logo部分 -->
      <div class="logo-container">
        <img src="@/assets/logo.png" alt="Logo" class="logo">
        <h2 class="title">微信管理系统</h2>
      </div>

      <!-- 登录表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item class="login-button">
          <el-button
            :loading="loading"
            type="primary"
            class="login-submit"
            @click="handleLogin"
          >
            登 录
          </el-button>
        </el-form-item>

        <div class="register-link">
          没有账号？<router-link to="/register">立即注册</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import axios from 'axios'
import { Role } from '@/utils/permission'
import { setUserInfo } from '@/utils/userStore'

const router = useRouter()
const loading = ref(false)
const loginFormRef = ref<FormInstance>()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
        // 创建URLSearchParams对象序列化参数
        const params = new URLSearchParams();
        params.append('username', loginForm.username);
        params.append('password', loginForm.password);
      try {
        // 调用登录接口
        const response = await axios.post('/auth/login',
            params,{
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              }
            }
          );
        
        if (response.data.code === 200) {
          // 存储token
          localStorage.setItem('token', response.data.data.access_token)
          // 设置用户信息，从后端获取角色信息
          setUserInfo({
            id: response.data.data.userId,
            username: response.data.data.username || loginForm.username,
            role: response.data.data.user.role,
            avatar: response.data.data.avatar
          })
          
          ElMessage.success('登录成功')
          router.push('/dashboard')
        } else {
          ElMessage.error(response.data.msg || '登录失败')
        }
      } catch (error: any) {
        // 为了演示，在开发环境中模拟登录成功
        // if (process.env.NODE_ENV === 'development') {
        //   // 存储模拟token
        //   localStorage.setItem('token', 'dev-token')
        //
        //   // 模拟从后端获取的用户信息
        //   // 在实际项目中，这里应该是从后端接口返回的数据
        //   const mockUserResponse = {
        //     userId: '1',
        //     username: loginForm.username,
        //     role: Role.ADMIN, // 为了演示，默认使用管理员角色
        //     avatar: ''
        //   }
        //
        //   setUserInfo({
        //     id: mockUserResponse.userId,
        //     username: mockUserResponse.username,
        //     role: mockUserResponse.role,
        //     avatar: mockUserResponse.avatar
        //   })
        //
        //   ElMessage.success('开发环境登录成功')
        //   router.push('/dashboard')
        // } else {
        //   ElMessage.error(error.response?.data?.msg || '登录失败，请检查用户名和密码')
        // }
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped lang="scss">
.login-container {
  height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;

  .login-box {
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 12px;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);

    .logo-container {
      text-align: center;
      margin-bottom: 30px;

      .logo {
        width: 80px;
        height: 80px;
        margin-bottom: 16px;
      }

      .title {
        font-size: 24px;
        color: #333;
        margin: 0;
      }
    }

    .login-form {
      .el-input {
        --el-input-height: 44px;
        margin-bottom: 5px;
      }

      .login-button {
        margin-top: 30px;
        
        .login-submit {
          width: 100%;
          height: 44px;
          font-size: 16px;
        }
      }
    }

    .register-link {
      text-align: center;
      margin-top: 16px;
      font-size: 14px;
      
      a {
        color: #409EFF;
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
}
</style>
